package com.css.fxfzypg.modules.baseData.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.entity.HistoricalSeismicDataNew;
import com.css.fxfzypg.modules.baseData.entity.HistoricalSeismicDataVo;
import com.css.fxfzypg.modules.baseData.repository.HistoricalSeismicDataRepository;
import com.css.fxfzypg.modules.baseData.entity.HistoricalSeismicData;
import com.css.fxfzypg.modules.baseData.queryParams.HistoricalSeismicDataQueryParams;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.PlatformSessionUtils;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class HistoricalSeismicDataRepositoryImpl implements HistoricalSeismicDataRepository {
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    SysRoleService sysRoleService;

    @Override
    public void updateHistoricalSeismicData(HistoricalSeismicData historicalSeismicData) {

        String sql = "update sys_historicalseismicdata set  hsd_Time = :hsdTime ,hsd_longitude = :hsdLongitude ,text_hsd_time = :textHsdTime " +
                ",hsd_latitude = :hsdLatitude ,hsd_sgrade = :hsdSgrade , hsd_sdepth = :hsdSdepth , hsd_sintensity = :hsdSintensity " +
                ",hsd_precision = :hsdPrecision ,hsd_referencename =  :hsdReferencename ,update_time = :updateTime ,update_user = :updateUser " +
                "where hsd_id = '" + historicalSeismicData.getHsdId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(historicalSeismicData);
        namedParameterJdbcTemplate.update(sql, source);

    }

    @Override
    public void saveHistoricalSeismicData(HistoricalSeismicData historicalSeismicData) {
        String sql = "insert into sys_historicalseismicdata values(:hsdId, :hsdTime, :hsdLongitude, :hsdLatitude, :hsdSgrade, :hsdSdepth, :hsdSintensity, :hsdPrecision, :hsdReferencename, " +
                ":hsdStatus, :updateTime, :createTime, :createUser, :updateUser, :textHsdTime,:createName)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(historicalSeismicData);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public Map<String, Object> getAllHistoricalSeismicDataParams(HistoricalSeismicDataQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select * from sys_historicalseismicdata ");

        StringBuilder orderSql = new StringBuilder(" order by create_time desc");

        StringBuilder whereSql = new StringBuilder(" where hsd_status = '" + YNEnum.N.toString() + "'");

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdSgrade())) {
            whereSql.append(" and hsd_sgrade = '" + queryParams.getHsdSgrade() + "'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdSintensity())) {
            whereSql.append(" and hsd_sintensity = '" + queryParams.getHsdSintensity() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdReferencename())) {
            whereSql.append(" and hsd_referencename like '%" + queryParams.getHsdReferencename() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCreateName())) {
            whereSql.append(" and create_name like '%" + queryParams.getCreateName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdTime())) {
            whereSql.append(" and hsd_time >= '" + queryParams.getHsdTime() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getEndTime())) {
            whereSql.append(" and hsd_time <= '" + queryParams.getEndTime() + "'");
        }

        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;
        sql.append(whereSql).append(orderSql).toString();
        StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(HistoricalSeismicData.class)).size();
        List<HistoricalSeismicDataNew> anrrsmEntities = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(HistoricalSeismicDataNew.class));

        //权限判断
        String userId = PlatformSessionUtils.getUserId();
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        for (HistoricalSeismicDataNew anrrsmEntity : anrrsmEntities) {
            if (anrrsmEntity.getCreateUser().equals(userId)){
                anrrsmEntity.setRole("0");
            }else {
                anrrsmEntity.setRole("1");
            }
        }
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)||allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)){
            anrrsmEntities.stream().peek(o ->o.setRole("0"));
        }
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", anrrsmEntities);
        return map;
    }

    @Override
    public HistoricalSeismicData getHistoricalSeismicDataById(String id) {
        String sql = "select * from sys_historicalseismicdata where hsd_id = '" + id + "'";
        HistoricalSeismicData historicalSeismicData = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(HistoricalSeismicData.class));
        return historicalSeismicData;
    }

    @Override
    public List<HistoricalSeismicData> getHistoricalSeismicData() {
        String sql = "select * from sys_historicalseismicdata where hsd_status = '0'";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(HistoricalSeismicData.class));
    }

    @Override
    public void deleteHistoricalSeismicDatasById(List<String> ids) {
        String sql = "update sys_historicalseismicdata set hsd_status = '" + YNEnum.Y.toString() + "' where hsd_id in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    @Override
    public List<HistoricalSeismicDataVo> getVo(HistoricalSeismicDataQueryParams queryParams) {
        StringBuilder sql = new StringBuilder("select  hsd_id,to_char(hsd_time,'YYYY.MM.DD') hsd_time,hsd_longitude,hsd_latitude," +
                "hsd_sgrade,hsd_sdepth,hsd_sintensity,hsd_precision,hsd_referencename,hsd_status,update_time,create_time," +
                "create_user,update_user,text_hsd_time from sys_historicalseismicdata ");

        StringBuilder whereSql = new StringBuilder(" where hsd_status = '" + YNEnum.N.toString() + "'");

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdSgrade())) {
            whereSql.append(" and hsd_sgrade = '" + queryParams.getHsdSgrade() + "'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdSintensity())) {
            whereSql.append(" and hsd_sintensity = '" + queryParams.getHsdSintensity() + "'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdReferencename())) {
            whereSql.append(" and hsd_referencename like '%" + queryParams.getHsdReferencename() + "%'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdTime()) && !PlatformObjectUtils.isEmpty(queryParams.getEndTime())) {
            whereSql.append(" and hsd_time >= '" + queryParams.getHsdTime() + "' and hsd_time <= '" + queryParams.getEndTime() + "'");
        }

        sql.append(whereSql);

        List<HistoricalSeismicDataVo> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(HistoricalSeismicDataVo.class));

        return list;
    }

    @Override
    public List<HistoricalSeismicData> findFormDataListByParams(HistoricalSeismicDataQueryParams queryParams) {
        StringBuilder sql = new StringBuilder("select  hsd_id,hsd_time,hsd_longitude,hsd_latitude," +
                "hsd_sgrade,hsd_sdepth,hsd_sintensity,hsd_precision,hsd_referencename,hsd_status,update_time,create_time," +
                "create_user,update_user,text_hsd_time from sys_historicalseismicdata ");

        StringBuilder whereSql = new StringBuilder(" where hsd_status = '" + YNEnum.N.toString() + "'");

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdSgrade())) {
            whereSql.append(" and hsd_sgrade = '" + queryParams.getHsdSgrade() + "'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdSintensity())) {
            whereSql.append(" and hsd_sintensity = '" + queryParams.getHsdSintensity() + "'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdReferencename())) {
            whereSql.append(" and hsd_referencename like '%" + queryParams.getHsdReferencename() + "%'");
        }

        if (!PlatformObjectUtils.isEmpty(queryParams.getHsdTime()) && !PlatformObjectUtils.isEmpty(queryParams.getEndTime())) {
            whereSql.append(" and hsd_time >= '" + queryParams.getHsdTime() + "' and hsd_time <= '" + queryParams.getEndTime() + "'");
        }


        sql.append(whereSql);

        List<HistoricalSeismicData> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(HistoricalSeismicData.class));

        return list;
    }

    @Override
    public Integer countByCounty(String countyName) {
        return jdbcTemplate.queryForObject("select count(a.*) from sys_historicalseismicdata a,district_boundary_county t where st_intersects(st_geomfromtext('POINT('||a.hsd_longitude||' '||a.hsd_latitude||')',4490), t.geom) and a.hsd_status ='0'" +
                " and t.name='" + countyName + "'", Integer.class);
    }

    @Override
    public Integer countByCity(String cityName) {
        return jdbcTemplate.queryForObject("select count(a.*) from sys_historicalseismicdata a,district_boundary_city t where st_intersects(st_geomfromtext('POINT('||a.hsd_longitude||' '||a.hsd_latitude||')',4490), t.geom) and a.hsd_status ='0'" +
                " and t.name='" + cityName + "'", Integer.class);
    }

    @Override
    public Integer countByProvince(String name) {
        return jdbcTemplate.queryForObject("select count(a.*) from sys_historicalseismicdata a,district_boundary_province t where st_intersects(st_geomfromtext('POINT('||a.hsd_longitude||' '||a.hsd_latitude||')',4490), t.geom) and a.hsd_status ='0'" +
                " and t.name='" + name + "'", Integer.class);
    }

    @Override
    public Integer countByProvinceAndYear(String province, String taskYear) {
        return jdbcTemplate.queryForObject("select count(a.*) from sys_historicalseismicdata a,district_boundary_province t where st_intersects(st_geomfromtext('POINT('||a.hsd_longitude||' '||a.hsd_latitude||')',4490), t.geom) and t.name=? and (TO_CHAR(update_time, 'yyyy-MM-dd hh24:mi:ss') LIKE ? or TO_CHAR(create_time, 'yyyy-MM-dd hh24:mi:ss') LIKE ?) and a.hsd_status ='0'", Integer.class, province, taskYear + "%", taskYear + "%");
    }

}
